/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    useTheme, Button, InputLine, Input, TextArea, Select, Layer, Popover, PopoverRefer,
    PopoverContent, PopoverDescription, MenuList, MenuItem, PopoverClose, IconX, Text, LineColumn, ButtonRefComp, BlobInputList
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, SelectHookfork, useInputControlSure, useItemInputControl
} from "../../common/base";
import {EditStorageContext} from "../../StorageContext";
import {useDeleteAddSub} from "../../hook/useDeleteAddSub";
import {Each_ZdSetting, useTableEditor} from "../../hook/useRepTableEditor";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";


//方便不同模板和不同版本的可重复引用。文件目录管理，组件按照抽象性程度和参数配置的关联度，分级分层次，标识容易区分开。
// http://localhost:8673/uploadTUS/  const uppy =new Uppy().use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/', withCredentials:true });
// Don’t forget to keep the Uppy instance outside of your component. //new Uppy().use(Webcam);  //endpoint: 'https://tusd.tusdemo.net/files/'
// const uppy =new Uppy().use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/' });     【文档】https://uppy.io/docs/react/   meta:{liveDays: 957,isp:'63990a43f-6e9e-498f-84b6-aff9d7e4b211'},
//注意：endpoint一定要和后端授权登录一样的才行，否则没有cookie。  metadata:{name: file.name,contentType: file.type || 'application/octet-stream',emptyMetaKey: ''}
// const uppy =new Uppy({id:'Report', restrictions:{maxNumberOfFiles: 2,}})
//     .use(Tus, { endpoint: `${process.env.REACT_APP_BACK_END}/uploadTUS/`, withCredentials:true,
//     }).use(Webcam);
//加限制 restrictions:{maxFileSize: 6000,maxNumberOfFiles: 1, allowedFileTypes:['image/*', '.jpg', '.jpeg', '.png', '.gif']}

const itemA测点位置=['点图说明','_FILE_S部位','检测结果']
export const Surface=
  React.forwardRef((
    { children, show ,alone=true,redId,nestMd, repId}:InternalItemProps,  ref
  ) => {
      const theme = useTheme();
      const {modified,setModified,} =React.useContext(EditStorageContext) as any;
      const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置,);
      const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
      const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
          onSure({...inp, '_FILE_S部位': upfile});
          !modified && setModified(true);
      }, [inp, modified,onSure,setModified]);
      const [uploadDom]=useUppyUpload({ repId:repId!,
          maxFile:5, onFinish, storeObj: inp?._FILE_S部位
      });
    return (
      <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                           alone={alone}  label={'测厚点位置示图'}>
          <InputLine label='测厚点位置示图（文字说明）：'>
              <BlobInputList value={inp?.点图说明 || ''}   datalist={["参考上面的位置示图","参考上面设备编号 的位置示图"]}
                             onListChange={v => setInp({...inp, 点图说明: v || undefined}) } />
          </InputLine>
          测厚点位置示图：
          {uploadDom}
        检测结果:
        <TextArea  value={inp?.检测结果 ||''} rows={4}
                 onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
      </InspectRecordLayout>
    );
} );


const checkConfig测量仪=[['设备名称','设备名称'],['设备编号','设备编号'],['仪器型号','仪器型号'],['仪器编号','仪器编号'],
    ['仪器精度','仪器精度'],['耦合剂','耦合剂']];
const itemA测概要 = ['记录备注'];
checkConfig测量仪.forEach(([ _,aName], i:number)=> {
    itemA测概要.push(aName);
});
export const Instrument=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const [getInpFilter] = useMeasureInpFilter(null, itemA测概要,);
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const {line}=useDeleteAddSub(nestMd!, redId!,verId!,repId!);
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'壁厚测定-概要仪器'} column={0}>
                {line}
                <LineColumn  key={1} column={2}>
                  { checkConfig测量仪.map(([title,name], i:number)=> {
                        return  <InputLine key={i} label={title+`:`}>
                            <Input  value={inp?.[name] || ''}
                                    onChange={e => {
                                        inp[name] = e.currentTarget.value||undefined;
                                        setInp({...inp});
                                    } } />
                        </InputLine>
                  })}
                </LineColumn>
                （测厚记录尾随的）备注：
                <TextArea  value={inp?.记录备注 ||''} rows={8}
                           onChange={e => setInp({ ...inp, 记录备注: e.currentTarget.value||undefined}) } />
            </InspectRecordLayout>
        );
    } );

export const Measurement=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const getInpFilter = React.useCallback((par: any) => {
            const {测厚表,参见图} =par||{};
            return {测厚表,参见图};
        }, []);
        const {inp, setInp} = useItemInputControl({ ref });
        const [seq, setSeq] = React.useState<number | null>(null);   //表對象的當前一條。
        //复合型的状态管理做法。 多个字段聚合的；
        const [obj, setObj] = React.useState({no1:'',vl1:'',no2:'',vl2:'',no3:'',vl3:'',
            no4:'',vl4:'',no5:'',vl5:'',no6:'',vl6:''});
        React.useEffect(() => {
            let size =inp?.测厚表?.length;
            setSeq(size>0?  size-1:null);
        }, [inp]);
        function onModifySeq(idx:number,it:any){
            setObj(it);
            setSeq(idx);
        };
        function onDeleteSeq(idx:number,it:any){
            inp?.测厚表?.splice(idx,1);
            setInp({...inp,测厚表: [...inp?.测厚表] });
            setSeq(null);
        };
        function onInsertSeq(idx:number,it:any){
            inp?.测厚表?.splice(idx,0, obj);
            setInp({...inp,测厚表:[...inp?.测厚表] });
            setSeq(idx);
        };
        function onAddSeq(idx:number){
            let size =inp?.测厚表?.push(obj);
            setInp( (inp?.测厚表&&{...inp,测厚表:[...inp?.测厚表] } )  || {...inp,测厚表:[obj] } );
            setSeq((inp?.测厚表&&(size-1))  || 0 );
        };

        const editor=<Layer elevation={"sm"} css={{ padding: '0.25rem' }}>
            <div>
                <LineColumn  column={6}>
                    <InputLine label={`测点1编号`}>
                        <Input   value={obj.no1 ||''}   onChange={e =>setObj({...obj, no1: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl1 ||''}   onChange={e =>setObj({...obj, vl1: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点2编号`}>
                        <Input   value={obj.no2 ||''}   onChange={e =>setObj({...obj, no2: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl2 ||''}   onChange={e =>setObj({...obj, vl2: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点3编号`}>
                        <Input   value={obj.no3 ||''}   onChange={e =>setObj({...obj, no3: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl3 ||''}   onChange={e =>setObj({...obj, vl3: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点4编号`}>
                        <Input   value={obj.no4 ||''}   onChange={e =>setObj({...obj, no4: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl4 ||''}   onChange={e =>setObj({...obj, vl4: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点5编号`}>
                        <Input   value={obj.no5 ||''}   onChange={e =>setObj({...obj, no5: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl5 ||''}   onChange={e =>setObj({...obj, vl5: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点6编号`}>
                        <Input   value={obj.no6 ||''}   onChange={e =>setObj({...obj, no6: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl6 ||''}   onChange={e =>setObj({...obj, vl6: e.currentTarget.value} ) } />
                    </InputLine>
                </LineColumn>
                <Button onPress={() => {
                    if(seq !== null) {
                        inp?.测厚表?.splice(seq, 1, obj);
                        setInp({ ...inp, 测厚表: [...inp?.测厚表] });
                    }
                    else setInp({ ...inp, 测厚表: [obj] });
                } }
                >{inp?.测厚表?.length>0? `改一组就确认`: `新增一组`}</Button>
            </div>
        </Layer>;

        const instrumentTable=<div>
            {inp?.测厚表?.map((a:any,i:number)=>{
                return <React.Fragment  key={i}>
                    <div>{`${i+1}`}
                        <Popover>
                            <PopoverRefer css={{width: '-webkit-fill-available',maxWidth: '40rem' }}>
                                <ButtonRefComp  size="md" variant="ghost"  css={{ flexWrap: 'wrap',
                                        width: '-webkit-fill-available', justifyContent: 'space-between',
                                        height: 'unset', minHeight: '32px', padding: 'unset' }}>
                                    <Text>{a.no1??''}:{a.vl1||'/'},</Text>
                                    <Text>{a.no2??''}:{a.vl2||'/'},</Text>
                                    <Text>{a.no3??''}:{a.vl3||'/'},</Text>
                                    <Text>{a.no4??''}:{a.vl4||'/'},</Text>
                                    <Text>{a.no5??''}:{a.vl5||'/'},</Text>
                                    <Text>{a.no6??''}:{a.vl6||'/'}</Text>
                                </ButtonRefComp>
                            </PopoverRefer>
                            <PopoverContent>
                                <PopoverDescription>
                                    <MenuList>
                                        <MenuItem onPress={()=>onModifySeq(i,a)}>修改</MenuItem>
                                        <MenuItem onPress={()=>onDeleteSeq(i,a)}>刪除这条</MenuItem>
                                        <MenuItem onPress={()=>onInsertSeq(i,a)}>插入一条</MenuItem>
                                        <MenuItem onPress={()=>onAddSeq(i)}>末尾新增一条</MenuItem>
                                    </MenuList>
                                </PopoverDescription>
                                <PopoverClose>
                                    <IconX/>
                                </PopoverClose>
                            </PopoverContent>
                        </Popover>
                    </div>
                    {i===seq && editor}
                </React.Fragment>;
            }) }
        </div>;

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'壁厚测定-测厚记录'}>
                <Text  variant="h5">
                测 厚 记 录 （ 测点厚度单位：㎜）；
                </Text>
                按照每一行布局6个测厚点为一组方式录入的，允许某些方格空缺:
                <hr/>
                {instrumentTable}
                {seq===null && editor}
                <Text variant="h6">
                 不在这录入测厚记录的，请输入说明：
                </Text>
                <InputLine  label='参见单线图吗？' >
                    <BlobInputList  value={inp?.参见图 ||''} datalist={['详见管道单线图']}
                                    onListChange={v => setInp({ ...inp, 参见图: v || undefined}) } />
                </InputLine>
            </InspectRecordLayout>
        );
    } );

export const config附设装置=[['附表序号','n',35],['设备种类','y',150,(obj,setObj)=>{
    return <Select inputSize="md" css={{minWidth:'140px',fontSize:'1.3rem',padding:'0 1rem'}}
                   value={obj?.y ||''} onChange={e => setObj({ ...obj, y: e.currentTarget.value||undefined}) }>
        <option></option> <option>桥架型起重机、臂架型起重机、电动葫芦等起重设备</option> <option>升降机等登机设备</option> </Select>
}],['设备名称','t',80],['设备型号','m',70],['额定起重量','Q',50],
    ['产品编号','p',68],['制造单位','u',112],['检验结果','r',35,(obj,setObj)=>{
        return <SelectHookfork value={ obj?.r ||''} onChange={e => setObj({ ...obj, r: e.currentTarget.value||undefined}) }/>
    }],['备注','Z',80]] as Each_ZdSetting[];
const 默认附设装置=[{n:'1',y:'桥架型起重机、臂架型起重机、电动葫芦等起重设备'},{n:'2',y:'桥架型起重机、臂架型起重机、电动葫芦等起重设备'},{n:'3',y:'升降机等登机设备'}];
export const config部位汇总=[['部位名称','n',125],['材质','c',95],['公称厚度mm','t',75],['腐蚀裕量mm','f',75],
               ['表面状况','b',90],['实测点数','d',55],['实测最小壁厚mm','r',90]] as Each_ZdSetting[];
// const 默认漏磁检=[{n:'直管'}];
const itemA部位汇总=['部位表'];
export const PartSummary=
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA部位汇总,);
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const headview=<Text variant="h5">
            壁厚测定：各部位实测点数和最小壁厚的汇总。
        </Text>;
        const [render部位汇总]=useTableEditor({inp, setInp,  headview,
            config: config部位汇总, table:'部位表', column:4,  maxRf:3});

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'壁厚各部位测点和最小壁厚'}>
                {render部位汇总}
            </InspectRecordLayout>
        );
    } );

